<template>
  <div>
    <div style="padding-bottom:5px">
      <el-select v-model="select" @change="grsChange">
        <el-option v-for="(item,i) in graphsList" :key="item.grsNo" :label="item.grsName" :value="i">
        </el-option>
      </el-select>
      <el-button-group>
        <el-button type="primary" icon="plus" size="small" @click="addDashBorad()">添加业务页</el-button>
        <el-button type="primary" icon="edit" size="small" @click="editDashBorad()">编辑业务页</el-button>
        <el-button type="primary" icon="delete" size="small" @click="delDashBorad()">删除业务页</el-button>
        <el-button type="primary" icon="share" size="small" @click="sendToMenu()">发布到菜单</el-button>

      </el-button-group>
      <el-button-group>
        <el-button type="primary" icon="setting" size="small" @click="setWidget()">选择业务</el-button>
        <!-- <el-button type="primary" icon="picture " size="small" @click="fullScreen()">全屏显示</el-button> -->
        <el-button type="primary" icon="setting" size="small" @click="saveWidget()">保存布局</el-button>

      </el-button-group>
    </div>
    <designer ref="designer" :keyMap="keyMap" :parentDesignerData='desigerData' :gridsterId="graphId"></designer>

    <el-dialog :modal=true v-model="dashBoradDialogVisible">
      <el-form :model="dashBoradForm" :rules="rules" ref="dashBoradForm" label-width="100px">
        <el-form-item label="操作">
          <el-button type="primary" @click="saveDashBorad()" size="small">保存</el-button>
          <el-button @click="dashBoradDialogVisible = false" size="small">取消</el-button>
        </el-form-item>
        <el-form-item label="图形名称" prop="grsName">
          <el-input v-model="dashBoradForm.grsName"></el-input>
        </el-form-item>
        <el-form-item label="图形编号" prop="grsNo">
          <el-input v-model="dashBoradForm.grsNo"></el-input>
        </el-form-item>
        <el-form-item label="图形参数" prop="params">
          <el-input type="textarea" v-model="dashBoradForm.params"></el-input>
        </el-form-item>
        <el-form-item label="图形样式" prop="style">
          <el-input type="textarea" v-model="dashBoradForm.style"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="dashBoradForm.remark"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="选择业务拓扑" :modal=true v-model="routerDialogVisible" size="tiny">
      <component :is="currentView" ref="businessChosser" transition="fade" transition-mode="out-in" keep-alive></component>
      <div style="padding-bottom:5px;float:right">
        <el-button type="primary" icon="save" size="small" @click="draw()">确定</el-button>
        <el-button type="primary" icon="cancel" size="small" @click="routerDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import designer from './designer.vue'
import businessChosser from './businessChooser.vue'
import eventHubs from 'common/eventHubs'
import api from 'api/graph.js'

export default {
  name: 'businessStatus',
  data() {
    var t = new Date();
    require("jquery.fullscreen");
    return {
      keyMap: { outEdit: 'true' },
      desigerData: {},
      graphsList: [],
      select: '',
      graphsType: '12',
      inputParams: {},
      graphId: "dashboard-" + t.getTime(),
      dashBoradDialogVisible: false,
      routerDialogVisible: false,
      currentView: null,
      dashBoradForm: {
        grsName: '',
        grsType: '12',
        grsNo: '',
        remark: ''
      },
      rules: {
        grsName: [
          { required: true, message: '请输入图形名称', trigger: 'blur' },
          { max: 200, message: '长度不超过 200 个字符', trigger: 'blur' }
        ],
        grsNo: [
          { required: true, message: '请输入图形编号', trigger: 'blur' },
          { max: 32, message: '长度不超过 32 个字符', trigger: 'blur' }
        ],
        params: [
          { max: 2000, message: '长度不超过 2000 个字符', trigger: 'blur' }
        ],
        style: [
          { max: 2000, message: '长度不超过 2000 个字符', trigger: 'blur' }
        ],
      },
      handelMode: ""
    }
  },
  mounted() {
    this.queryData();
  },
  methods: {
    queryData() {
      api.listGraphs(this.graphsType).then((response) => {
        let data = response.data;
        this.graphsList = data;
        if (this.handelMode == "insert") {//新增flag，选择最后一个选项
          this.select = this.graphsList.length - 1;
          this.dashBoradForm = this.graphsList[this.select];
          this.desigerData = {
            grsNo: this.dashBoradForm.grsNo
          };
          this.handelMode = "";
        } else if (this.select === '') {//没有选择选择第一个选项
          if (data[0]) {
            this.select = 0;
            this.dashBoradForm = this.graphsList[this.select];
            this.desigerData = {
              grsNo: this.dashBoradForm.grsNo
            };
          }
        } else if (!data || data.length == 0) {//没有选择选择第一个选项
          this.select = '';
          this.dashBoradForm = {
            grsName: '',
            grsType: '12',
            grsNo: '',
            remark: ''
          };
          this.desigerData = {
            grsNo: ''
          };
        } else {
          this.$refs.designer.init();
        }
      }).catch((err) => {
        console.error(err);
      });
    },
    grsChange() {
      if (this.graphsList[this.select]) {
        this.dashBoradForm = this.graphsList[this.select];
        this.desigerData = {
          grsNo: this.dashBoradForm.grsNo
        };
      }
    },
    fullScreen() {
      $('#' + this.graphId).fullScreen();
    },
    addDashBorad() {
      this.dashBoradForm = {
        grsName: '',
        grsType: '12',
        grsNo: '',
        remark: ''
      };
      this.handelMode = "insert";
      this.dashBoradDialogVisible = true;
    },
    editDashBorad() {
      this.dashBoradForm = this.graphsList[this.select];
      this.dashBoradDialogVisible = true;
    },
    saveDashBorad() {
      //表单信息
      var formData = this.dashBoradForm;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          api.saveGraphs(formData).then((response) => {
            //同步表单数据（主要是新增的是获取新的ID）
            this.dashBoradForm = response.data;
            this.dashBoradDialogVisible = false;
            eventHubs.getEventHub().$emit("getMenuList");
            this.queryData();
            this.$message({
              showClose: true,
              message: "保存成功！"
            });
          }).catch((err) => {
            this.$message({
              showClose: true,
              message: "保存失败：" + err.data.errorMsg
            });
          });
        } else {
          return false;
        }
      });
    },
    delDashBorad() {
      this.$confirm('是否删除该业务监控页?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteGraphs(this.dashBoradForm["id"]).then((response) => {
          this.select = '';
          eventHubs.getEventHub().$emit("getMenuList");
          this.queryData();
        }).catch((err) => {
          console.error(err);
        });
      });
    },
    setWidget() {
      if (this.graphsList.length == 0 || (this.select == '' && this.select != 0)) {
        this.$message({
          showClose: true,
          message: '请先选择或添加一个业务监控页！'
        });
        return false;
      }
      this.currentView = businessChosser;
      this.routerDialogVisible = true;
    },
    draw() {
      //获取选中的图形列表
      let sysMaps = this.$refs.businessChosser.selectSysMaps;
      let widgetJson = [];
      if (sysMaps.length == 0) {
        this.$message({
          showClose: true,
          message: '至少选中一个图形！'
        });
        return false;
      }
      if (sysMaps.length > 25) {
        this.$message({
          showClose: true,
          message: '最多选择24个图形，请注意拆分业务！'
        });
        return false;
      }

      for (let i = 0; i < sysMaps.length; i++) {
        let y = parseInt(i / 3) * 7 + 1;
        let x = (i % 4) * 2 + 1;
        let obj = sysMaps[i];
        widgetJson.push({
          "col": x,
          "row": y,
          "size_x": 2,
          "size_y": 7,
          "form": {
            "chartName": obj.name,
            "chartType": "business",
            "refFlag": "0",
            "refMs": "30000",
            "option": {
              "value": "business-health-detail.health_rate,busy_rate,health,colKey,colNum",
              "health_rateKey": "health_rate",
              "busy_rateKey": "busy_rate",
              "healthKey": "health",
              "colKeyKey": "colKey",
              "colNumKey": "colNum",
              "backgroundColor": "white",
              "fontColor": "black",
              "params": JSON.stringify({ sysmapid: obj.sysmapid })
            }
          }
        });
      }
      this.dashBoradForm.widgetData = JSON.stringify(widgetJson);
      this.saveDashBorad();
      this.routerDialogVisible = false;
    },
    sendToMenu() {
      this.$confirm('是否发布监控页到【业务监控】菜单下?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var formData = this.dashBoradForm;
        console.log('formData');
        console.log(formData);
        api.sendToMenu(formData, 'ReportMgm', 'Business Monitor').then((response) => {
          //同步表单数据（主要是新增的是获取新的ID）
          eventHubs.getEventHub().$emit("getMenuList");
        }).catch((err) => {
          console.error(err);
        });
      });

    },
    saveWidget() {
      this.$refs.designer.doSave(true);
    }
  },
  components: {
    designer, businessChosser
  }
}
</script>
